<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Order extends Model
{
    use SoftDeletes;

    const REFUND = -2;
    const CANCEL = -1;
    const TO_PAY = 0;
    const PAID = 1;
    const FINISHED = 2;

    const SERVICE_ORDER = 'service';

    public static $statusArr = [
        -2 => '已退款',
        -1 => '已取消',
        0 => '待支付',
        1 => '已支付',
        2 => '已完成'
    ];
    protected $table = 'orders';

    public $fillable = [
        'order_no', 'user_id', 'fee', 'goods_id', 'goods_type', 'status'
    ];

    //查询用户名称
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function goods()
    {
        if($this->goods_type == 'service'){

        }else{
            return $this->morphTo('goods','goods_type','goods_id');
        }
    }


    public function getHumanStatusAttribute()
    {
        return array_get(self::$statusArr, $this->status);
    }


    //判断订单是否可以分成
    public function isServiceOrder()
    {
        return $this->getOriginal('goods_id') > 0;
        //return $this->getOriginal('goods_type') == self::SERVICE_ORDER;
    }

    public function isPaid()
    {
        return self::PAID == $this->getOriginal('status');
    }

    public function isNeedToPay()
    {
        return self::TO_PAY == $this->getOriginal('status');
    }


    public function getPayFee()
    {
        return $this->fee;
    }


    public function paid()
    {
        if ($this->isNeedToPay()) {
            $this->update([
                'status' => self::PAID
            ]);
        }
    }
    public function package()
    {
        return $this->hasOne(Package::class, 'id','goods_id');
    }
    public function grip()
    {
        return $this->hasOne(Grip::class, 'id','grip_id');
    }

    /**
     * 创建订单
     * @param Authenticatable $user 当前登录用户 必选
     * @param int $fee 订单金额 必选
     * @param int $goodsId 商品id 如果是服务类型 则为0 默认为0
     * @param string $goodsType 商品类型  包括套餐 押金 柜子等信息
     * @param string $addition 商品附加信息
     * @return Order 返回订单实例
     */
    public static function generate(Authenticatable $user, int $fee, $goodsId = 0, $goodsType = 'service', $addition = ''): Order
    {
        $orderNo = generateOrderNo($goodsId);
        return self::create([
            'order_no' => $orderNo,
            'user_id' => $user->id,
            'fee' => $fee,
            'goods_id' => $goodsId,
            'goods_type' => $goodsType,
            'addition' => $addition,
            'status' => self::TO_PAY,
        ]);
    }

}
